package com.huantai.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.huantai.auth.util.JWTUtil;
import com.huantai.common.controller.BaseRestController;
import com.huantai.common.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangpeipei
 * @date 2020/5/12 17:35
 */
@Slf4j
@RestController
@RequestMapping("/")
public class AuthController extends BaseRestController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    JWTUtil jwtUtil;

    /**
     * 登录认证
     *
     * @param username 用户名
     * @param password 密码
     */
    @GetMapping("/login")
    public BaseResponse login(@RequestParam String username, @RequestParam String password) {
        //生成token
        String token = jwtUtil.generateToken(username);

        //生成refreshToken
        String refreshToken = UUID.randomUUID().toString();

        //数据放入redis
        redisTemplate.opsForHash().put(refreshToken, "token", token);
        redisTemplate.opsForHash().put(refreshToken, "username", username);

        //设置token的过期时间
        redisTemplate.expire(refreshToken, jwtUtil.getValidTime(), TimeUnit.MILLISECONDS);

        JSONObject result = new JSONObject();
        result.put("token", token);
        result.put("refreshToken", refreshToken);
        return succResponse(result);
    }

    /**
     * 刷新token
     */
    @GetMapping("/refreshToken")
    public BaseResponse refreshToken(@RequestParam String refreshToken) {
        String username = (String) redisTemplate.opsForHash().get(refreshToken, "username");
        if (StringUtil.isEmpty(username)) {
            return new BaseResponse("1003", "refreshToken error");
        }

        //生成新的token
        String newToken = jwtUtil.generateToken(username);
        redisTemplate.opsForHash().put(refreshToken, "token", newToken);

        JSONObject result = new JSONObject();
        result.put("token", newToken);
        result.put("refreshToken", refreshToken);
        return succResponse(result);
    }

}
